package cn.reone.mbt.ui;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.ListViewCompat;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.reone.mbt.R;
import cn.reone.mbt.util.PermissionUtil;

public class MainActivity extends AppCompatActivity {
    @BindView(R.id.activity_main)
    LinearLayout activityMain;
    @BindView(R.id.onoff_btn)
    AppCompatButton onoffBtn;
    @BindView(R.id.showinfo_btn)
    AppCompatButton showinfoBtn;
    @BindView(R.id.scan_device)
    AppCompatButton scanDevice;
    @BindView(R.id.device_list)
    ListViewCompat deviceList;
    @BindView(R.id.ready_tv)
    AppCompatTextView readyTv;


    private BluetoothAdapter mBluetoothAdapter;
    private String adapterInfo;
    private static final int REQUEST_ENABLE_BT = 1;
    private ArrayList<BluetoothDevice> mPairedDevices = new ArrayList<>();
    private DeviceAdapter deviceAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        deviceAdapter = new DeviceAdapter(mPairedDevices, this);
        deviceList.setAdapter(deviceAdapter);
        deviceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(MainActivity.this, ClientActivity.class);
                BluetoothDevice device = deviceAdapter.getItem(position);
                if (device == null) return;
                intent.putExtra(ClientActivity.BLUETOOTH_DEVICE, device);
                startActivity(intent);
            }
        });
        updateInfo();
        Logger.d(adapterInfo);
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadReadyData();
        PermissionUtil.requestPermissionWithCheck(this, Manifest.permission.ACCESS_FINE_LOCATION
                , PermissionUtil.REQUESTCODE_ACCESS_FINE_LOCATION, "Android 6.0增加了对附近设备扫描的权限限制");
    }

    /**
     * 蓝牙开关
     *
     * @param view
     */
    @OnClick(R.id.onoff_btn)
    public void onoff(View view) {
        if (mBluetoothAdapter == null) return;
        if (mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.disable();
            Logger.d("蓝牙关闭");
        } else {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
        updateInfo();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_ENABLE_BT:
                    Logger.d("蓝牙开启成功");
                    loadReadyData();
                    break;
            }
        }
    }

    /**
     * 可被发现
     *
     * @param view
     */
    @OnClick(R.id.enable_search)
    public void enableSearch(View view) {
        if (mBluetoothAdapter == null) return;
        if (!mBluetoothAdapter.isEnabled()) {
            talk("蓝牙不能使用");
            return;
        }
        Intent enable = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        enable.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 120); //3600为蓝牙设备可见时间
        startActivity(enable);
        Logger.d("蓝牙允许检测");
        updateInfo();
    }

    /**
     * 显示蓝牙状态
     *
     * @param view
     */
    @OnClick(R.id.showinfo_btn)
    public void showInfo(View view) {
        if (adapterInfo == null || adapterInfo.equals("")) {
            talk("蓝牙信息为空");
        } else {
            Logger.d("显示蓝牙信息\n" + adapterInfo);
            new AlertDialog.Builder(this)
                    .setMessage(adapterInfo)
                    .create()
                    .show();
        }
    }

    /**
     * Toast
     *
     * @param str
     */
    private void talk(String str) {
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
        Logger.d(str);
    }

    /**
     * 更新蓝牙状态
     */
    private void updateInfo() {
        StringBuffer sb = new StringBuffer();
        sb.append("name : " + mBluetoothAdapter.getName()
                + "\naddress : " + mBluetoothAdapter.getAddress()
                + "\nstate : " + mBluetoothAdapter.getState()
                + "\nmode : " + mBluetoothAdapter.getScanMode()
                + "\nisEnabled : " + mBluetoothAdapter.isEnabled()
                + "\nisDiscovering : " + mBluetoothAdapter.isDiscovering()
        );
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            sb.append("\nMultipleAdvertisement : " + mBluetoothAdapter.isMultipleAdvertisementSupported());
            sb.append("\nOffloadedFiltering : " + mBluetoothAdapter.isOffloadedFilteringSupported());
            sb.append("\nisOffloadedScanBatching : " + mBluetoothAdapter.isOffloadedScanBatchingSupported());
        }
        adapterInfo = sb.toString();
    }

    /**
     * 扫描设备
     *
     * @param view
     */
    @OnClick(R.id.scan_device)
    public void scanDevice(View view) {
        startActivity(new Intent(this, ScanActivity.class));
    }

    /**
     * 加载已配对设备
     */
    private void loadReadyData() {
        if (mBluetoothAdapter == null) {
            talk("adapter为空");
            return;
        }
        mPairedDevices.clear();
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            readyTv.setText(getString(R.string.ready_device));
            for (BluetoothDevice device : pairedDevices) {
                mPairedDevices.add(device);
            }
        } else {
            readyTv.setText("无匹配设备");
        }
        deviceAdapter.reflush(mPairedDevices);
    }

    @OnClick(R.id.scan_ready)
    public void scanReady() {
        loadReadyData();
        talk("列表已更新");
    }

    @OnClick(R.id.create_server)
    public void createServer() {
        startActivity(new Intent(this, ServerActivity.class));
    }

    @OnClick(R.id.scan_ble_device)
    public void scanBleDevice() {
        startActivity(new Intent(this,ScanBleActivity.class));
    }
}
